//---------------------------------------------------------------------------


#pragma hdrstop

#include "TNotes.h"

//---------------------------------------------------------------------------

#pragma package(smart_init)
TNotes::TNotes(Client* client)
{
	if(NULL==client)return;
	_client=client;
	notes=new  Annotations(_client);
	notes->registerAnnotationsHandler( this );
}
//---------------------------------------------------------------------------
TNotes::~TNotes()
{

	if(notes){
			notes->removeAnnotationsHandler();
			delete notes;
		}
}
//---------------------------------------------------------------------------
void TNotes::handleAnnotations( const AnnotationsList &aList )
{
	 AnnotationsList::const_iterator it = aList.begin();
	  for( ; it != aList.end(); it++ )
	  {
		 if((*it).jid==EmptyString||(*it).note==EmptyString)continue;
		 if(FOnNotes)FOnNotes((*it).jid.c_str(),
				(*it).note.c_str(), (*it).cdate.c_str(), (*it).mdate.c_str());
	  }
	  lists=aList;
}
//---------------------------------------------------------------------------
void __fastcall TNotes::GetNotes()
{
     if(_client->state()!=StateConnected)return;
	   notes->requestAnnotations();
}
//---------------------------------------------------------------------------
AnnotationsList::iterator __fastcall TNotes::AddNote(std::string jid,std::string note,std::string ctime,std::string mtime)
{
	  if(jid==EmptyString||note==EmptyString||NULL==notes)return  lists.begin();
	  AnnotationsListItem bItem;
	  bItem.jid = jid;
	  bItem.note = note;
	  bItem.cdate = ctime;
	  bItem.mdate = mtime;
	  lists.push_back( bItem );
	  return lists.end();
}
//---------------------------------------------------------------------------
void __fastcall TNotes::SaveNotes()
{
     if(_client->state()!=StateConnected)return;
	 notes->storeAnnotations(lists);
}
//---------------------------------------------------------------------------
AnnotationsList::iterator __fastcall TNotes::EditNotes(unsigned int index,std::string jid,std::string note,std::string ctime,std::string mtime)
{
	 if(index>=lists.size()||lists.empty())return  lists.begin();
	 AnnotationsList::iterator it =lists.begin();
	 for(int i=0;i<index&&it!=lists.end();i++,it++);
	 lists.erase(it--);
	 it++;
	 AnnotationsListItem bItem;
	 bItem.jid = jid;
	 bItem.note = note;
	 bItem.cdate = ctime;
	 bItem.mdate = mtime;
	 lists.insert(it, bItem);
	 it--;
	 return it;
}
//---------------------------------------------------------------------------
AnnotationsList::iterator __fastcall TNotes::DeleteNote(int index)
{
	  if(index>=lists.size())return lists.begin();
	  if(index==-1)
	  {	lists.clear();
			return lists.begin();
	  }

		  AnnotationsList::iterator it = lists.begin();
		  for(int i=0;i<index&&it!=lists.end();i++,it++);
		  lists.erase(it--);
		  if(lists.empty())
			return lists.begin();
		  else
			return it++;

}
